<template>
  <div class="container" style="padding: 10px">
    <el-card>
      <div slot="header" class="clearfix" v-if="this.$route.query.name">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{ this.$route.query.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :inline="true" :model="directory" class="demo-form-inline">
        <el-row type="flex" justify="space-between">
          <el-col>
            <el-form-item label="标签名称">
              <el-input
                v-model="directory.name"
                placeholder="请输入内容"
                type="text"
                style="width: 160px; margin-right: 10px"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select style="width: 160px; margin-right: 10px" v-model="directory.state" placeholder="状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="DeleteInput">清除</el-button>
              <el-button type="primary" @click="subjectsSearch">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-form-item>
            <el-button
              v-if="this.$route.query.name"
              @click="$router.replace(`/subjects/list`)"
              icon="el-icon-back"
              type="text"
              >返回学科</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-edit" type="success" @click="addsubjects"
              >新增标签</el-button
            >
          </el-form-item>
        </el-row>
        <el-alert
        :closable="false"
        :title="`数据一共 ${counts} 条`"
        type="info"
        show-icon
      >
      </el-alert>
      </el-form>
      <br>
      <el-table :data="data" :header-cell-style="{
        background: '#FAFAFA',
        color: '#909399',
        borderBottom: '2px solid #e8e8e8',
      }">
        <el-table-column type="index" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="subjectName" label="所属学科">
           <template v-slot="{ row }">
            {{row.subjectName?row.subjectName:'无名称'}}
           </template>
        </el-table-column>
        <el-table-column prop="tagName" label="标签名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者">
        </el-table-column>
        <el-table-column prop="addDate" label="创建日期" width="250">
          <template v-slot="{ row }">
            {{
              new Date(+new Date(row.addDate) + 8 * 3600 * 1000)
                .toISOString()
                .replace(/T/g, " ")
                .replace(/\.[\d]{3}Z/, "")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="130">
          <template v-slot="{ row }">
            {{ +row.state ? "已启用" : "已禁用" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="id" width="300">
          <template v-slot="{ row }">
            <el-button
              type="text"
              v-if="!row.state"
              :disabled="false"
              @click="changeState(row)"
              >启用</el-button
            >
            <el-button
              type="text"
              v-else
              :disabled="false"
              @click="changeState(row)"
              >禁用</el-button
            >
            <el-button type="text" :disabled="!!row.state" @click="update(row)"
              >修改</el-button
            >
            <el-button
              type="text"
              :disabled="!!row.state || row.id === 2"
              @click="remove({ id: row.id })"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[1, 5, 10, 20]"
          :page-size.sync="list.pagesize"
          layout=" prev, pager, next,sizes, jumper"
          :total="counts"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="400px"
      @close="handleClose"
    >
      <span>
        <el-form
          :model="ruleInfo"
          :rules="rules"
          ref="ruleForm"
          label-position="right"
        >
          <el-form-item
            v-if="!this.$route.query.name"
            label="所属学科"
            prop="val1"
            label-width="80px"
          >
            <el-select
              v-model="ruleInfo.val1"
              placeholder="请选择"
              style="width: 80%"
            >
              <el-option
                v-for="(item, index) in Subject_data"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称"  prop="val2" label-width="80px">
            <el-input
              v-model.trim="ruleInfo.val2"
              placeholder="请输入内容"
              type="text"
              style="width: 80%"
            ></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="bthOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import {
  list, add, update, remove, changeState,
  simple as simple1
} from '@/api/hmmm/tags.js'
export default {
  data () {
    const tagsRules = async (rule, value, callback) => {
      let list = []
      if (this.$route.query.id) {
        const { data } = await simple1({
          subjectID: this.$route.query.id
        })
        list = data
      } else {
        const { data } = await simple1({
          subjectID: this.ruleInfo.val1
        })
        list = data
      }
      console.log(list)
      let isRepeat
      list.forEach(item => {
        if (item.label === value) {
          isRepeat = true
        }
      })
      isRepeat ? callback(new Error('当前学科下已有该标签')) : callback()
    }
    return {
      subjectID: 1,
      val3: '3',
      Subject_data: [],
      butShow: true,
      directory: {
        name: '',
        state: null
      },
      title: '新增标签',
      ruleInfo: {
        id: '',
        val1: '',
        val2: ''
      },
      dialogVisible: false,
      input: '',
      data: [],
      counts: null,
      list: {
        pagesize: 10,
        page: 1,
        tagName: '',
        state: null
      },
      rules: {
        val1: [{ required: true, message: '请选择所属学科', trigger: 'change' }],
        val2: [{ required: true, message: '请输入标签名称', trigger: 'change' },
          { min: 1, max: 10, message: '要求1-10个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: tagsRules
          }]
      }
    }
  },
  created () {
    this.simple()
    if (this.$route.query.id && this.$route.query.name) {
      this.subjectsSearch(this.$route.query.id, this.$route.query.name)
    } else {
      this.list1()
    }
  },
  watch: {
    $route: {
      handler: function (val, oldVal) {
        if (!val.query.id) {
          this.list.subjectID = null
          this.list1()
        }
      },
      // 深度观察监听
      deep: true
    }
  },
  methods: {
    async changeState (row) {
      const data = {
        id: row.id,
        state: row.state === 1 ? 0 : 1
      }
      await changeState(data)
      this.list1()
    },
    async simple () {
      const { data } = await simple()
      this.Subject_data = data
    },
    remove (data) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(data)
        this.list1()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).then(() => {
        if (this.data.length === 1) {
          console.log(666)
          this.list.page = this.list.page - 1
          if (!this.list.page) {
            this.list.page = 1
          }
          this.list1()
        } else {
          console.log(this.data[0])
        }
      }).catch((error) => {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        } else {
          console.log(error)
        }
      })
    },
    addsubjects () {
      this.title = '新增标签'
      this.dialogVisible = true
    },
    update (row) {
      this.title = '修改标签'
      this.dialogVisible = true
      this.ruleInfo.id = row.id
      this.ruleInfo.val1 = row.subjectID
      this.ruleInfo.val2 = row.tagName
    },
    async bthOk () {
      if (this.title === '修改标签') {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const data = {
                id: this.ruleInfo.id,
                subjectID: this.ruleInfo.val1,
                tagName: this.ruleInfo.val2
              }
              // console.log(data)
              await update(data)
              this.list1()
              this.handleClose()
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log('999')
            return false
          }
        })
      } else {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const data = {
                subjectID: this.ruleInfo.val1,
                tagName: this.ruleInfo.val2
              }
              if (this.$route.query.name) {
                data.subjectID = +this.$route.query.id
              }
              await add(data)
              this.list1()
              this.handleClose()
              this.$message({
                message: '新增成功',
                type: 'success'
              })
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log('999')
            return false
          }
        })
      }
    },
    handleClose () {
      this.ruleInfo = {
        id: '',
        val1: '',
        val2: ''
      }
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    },
    DeleteInput () {
      this.directory.name = ''
      this.directory.state = null
      // 无用逻辑代码+1
      // this.subjectsSearch()
    },
    subjectsSearch (e, a) {
      if (e && a) {
        console.log(9)
        this.list.subjectID = e
      } else {
        this.list.tagName = this.directory.name
        // console.log(this.list.directoryName)
        this.list.state = this.directory.state
      }
      this.list1()
      this.list.page = 1
    },
    handleSizeChange (val) {
      this.list.pagesize = val
      this.list1()
    },
    handleCurrentChange (val) {
      this.list.page = val
      this.list1()
    },
    async list1 () {
      const { data } = await list(this.list)
      this.data = data.items
      this.counts = data.counts
      this.list.pagesize = +data.pagesize
      // console.log(data)
      // console.log(this.data)
    }
  }
}
</script>

<style scoped lang="less">
.demo-form-inline{
width: 100%;
Min-width:820px;
}
</style>
